﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using System.Text.RegularExpressions;

namespace Oracle.Lexer;

[Order(0)]
public class TriggerLexer : BaseLexer
{
    public override bool Check()
        => Txt.StartsWith("CREATE OR REPLACE TRIGGER");

    protected override BaseCodeEntity Run()
    {
        var all = Txt;
        var txt = Regex.Match(all, ".*?BEGIN").Value.Replace("\"", "").Replace("÷", "").Trim();
        var name = Regex.Match(txt, "\\.(.*?)\\s").Result("$1").Trim();
        var time = Regex.Match(txt, "((BEFORE|AFTER).*?)ON").Result("$1").Trim();
        var table = Regex.Match(txt, "ON\\s(.*?)\\s").Result("$1").Trim();
        var entity = new TriggerCodeEntity(name, time, table);
        if (txt.Contains("DECLARE"))
        {
            var declares = Regex.Match(txt, "DECLARE(.*?)BEGIN").Result("$1").Trim();
            var arr = declares.TrimSplit(';');
            entity.Declare = [];
            foreach (var item in arr)
            {
                if(string.IsNullOrEmpty(item)) continue;
                entity.Declare.Add(SqlFactory.Create(item).Execute());
            }
        }
        entity.IsRow = txt.Contains("FOR EACH ROW");
        var body = Regex.Match(all, "BEGIN.*END").Value.Trim();
        entity.Body = SqlFactory.Create(body).Execute();
        return entity;
    }
}
